let http = require('http');
let fs = require("fs");
let nunjucks = require('nunjucks');
const Son = require('./home/controller/Son');

let serve = http.createServer(async function (req, res) {
    let url = req.url;
    console.log(url);
    if (url.lastIndexOf('.') > -1) {
        let path = '.' + url;
        // console.log(path);
        fs.exists(path, function (result) {
            if (!result) {
                path = './home/imgs/earth.png';
            }
            fs.readFile(path, function (err, date) {
                if (err) {
                    console.log(err.message);
                } else {
                    res.write(date);
                    res.end();
                }
            })
        })
    }else{
        let query = url.split('?')[1];
        // console.log(query);
        let queryarry = query.split('&')
        // console.log(queryarry);
        let newarr = [];
        for(let val in queryarry){
            console.log(queryarry[val]);
            let arrsplit = queryarry[val].split('=');
            newarr[arrsplit[0]] = arrsplit[1];
        }
        console.log(newarr);
        req.query = newarr;
        let action = newarr['name'];
        let son = new Son(req,res,nunjucks);
        let result = await son[action]();
        res.write(result);
    }
})
serve.listen(3000, function () {
    console.log("服务已启动: http://127.0.0.1:3000");
})